#!/usr/bin/env python

import os
import sys
import string
import traceback
import json

Count=0

def find_file_by_pattern(pattern='.*', base=".", circle=True): 
    if base == ".":  
        base = os.getcwd()  

    final_file_list = []  
    cur_list = os.listdir(base)  
    for item in cur_list:

        full_path = os.path.join(base, item)

        if item == ".svn" or item== ".git" :  
            continue  

        if os.path.isfile(full_path):  
            if full_path.endswith(pattern):  
                final_file_list.append(full_path)  
        else:
            if (True == circle):  
                final_file_list += find_file_by_pattern(pattern, full_path, circle)  
    return final_file_list


def gen_msg_id(path,package):
    global Count 
    msg_dict={}
    key = "message"
    fh = open(path)
    for line in fh.readlines():
        if line.startswith(key):
            messageName = line
            startPos = messageName.index(" ",len(key))
            endPos = messageName.find(" ",startPos+1)
            if endPos<0:
                endPos = messageName.find("{",startPos+1)

            if endPos<0:
                print "%s %d %d" % (messageName,startPos,endPos)

            messageName = line[startPos+1:endPos]

            Count+=1
            msg_dict[package+"_"+messageName]=Count
        
    return msg_dict


def main():
    outText="syntax = \"proto2\";\npackage dict;\n\n"

    msg_dict={}
    proto_files = find_file_by_pattern(".proto", ".", False)

    for proto in proto_files:
        package = os.path.basename(proto).replace(".proto","")
        for (k,v) in gen_msg_id(proto,package).items():
            msg_dict[k]=v

    outText+="enum EDict"+" {\n"
    for key, value in sorted(msg_dict.iteritems(), key=lambda (k,v): (v,k)):
        outText+="\t"+key+"="+str(value)+";\n"

    outText+="}\n"

    print outText

    outPath="dict.proto"
    try:
        output = open(outPath, 'w')
        output.write(outText)
        output.close()
    except Exception as e:
        raise Exception("error : create file failed")
   


if __name__ == '__main__':
    try:
        main()
    except Exception as e:
        traceback.print_exc()
        sys.exit(1)